﻿using QiBu.Api.Helper.Common;
using QiBu.Api.Map;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QiBu.Api.Attribute
{
    /// <summary>
    /// 登录特性
    /// </summary>
    public class SelfOnlyAttribute : FilterAttribute, IAuthorizationFilter, IActionFilter
    {
        protected SYS_User _currentUser;
        private string _parameter;

        public SelfOnlyAttribute(string parameter = "user")
        {
            this._parameter = parameter;
        }

        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            string controller = filterContext.RouteData.Values["controller"].ToString();
            string action = filterContext.RouteData.Values["action"].ToString();
            string userData = string.Empty;
            _currentUser = null;
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                _currentUser = FormLoginHelper<SYS_User>.Get();
            }
            else
            {
                var Request = filterContext.RequestContext.HttpContext.Request;
                var retUrl = Request.Url.AbsoluteUri.ToLower();
                retUrl = string.IsNullOrEmpty(retUrl) ? string.Empty : System.Web.HttpUtility.UrlEncode(retUrl, System.Text.Encoding.UTF8);
                filterContext.Result = new RedirectResult(string.Format("/user/login?returnUrl={0}", retUrl.ToLower()));
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Controller.ViewBag.CurrentUser = _currentUser;
            }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionParameters.ContainsKey(_parameter))
            {
                filterContext.ActionParameters[_parameter] = _currentUser;
            }
        }
    }
}